// pages/newtask/newtask.js
// import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog";
// const watch =require ('../../../payment/utils/util')
import Dialog from "../../miniprogram_npm/@vant/weapp/dialog/dialog";
import api from "../../utils/api";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coId: '',
    unitId: '',
    invid: '', //该发票id
    code: '', //该发票code
    keyId: '', //该发票keyId,税率
    columns: [], //下拉选
    showType: false, //展示下拉选择
    typeIndex: '',
    totalPrice: '',
    invFormContentList: '',
    noMoney: false,
    billList: [{
      content: '',
      contentCode: '',
      model: '',
      production: '',
      unit: '',
      num: '',
      price: '',
      money: '',
    }, ],
    code: ''
  },

  //规格型号 输入框变化
  onModelChange(e) {
    // event.detail 为当前输入的值
    let index = e.currentTarget.dataset.index;
    this.setData(
      this.data.billList[index].model = e.detail
    )
    // console.log(this.data.billList[index].model, "model")
  },
  onproductionChange(e) {
    let index = e.currentTarget.dataset.index;
    this.setData(
      this.data.billList[index].production = e.detail
    )
  },
  onunitChange(e) {
    let index = e.currentTarget.dataset.index;
    this.setData(
      this.data.billList[index].unit = e.detail
    )

  },
  onnumChange(e) {
    let index = e.currentTarget.dataset.index;
    this.setData(
      this.data.billList[index].num = e.detail,
    )
    if (this.data.billList[index].price) {
      this.setData(
        this.data.billList[index].money = e.detail * this.data.billList[index].price,
      )
    }
  },
  onpriceChange(e) {
    let index = e.currentTarget.dataset.index;
    this.setData(
      this.data.billList[index].price = e.detail,
    )
    if (this.data.billList[index].num) {
      this.setData(
        this.data.billList[index].money = e.detail * this.data.billList[index].num,
      )
    }
  },
  //金额  = 数量*单价
  onmoneyChange(e) {
    let index = e.currentTarget.dataset.index;
    let total = 0
    // 数量或单价为空
    if (!this.data.billList[index].num || !this.data.billList[index].price) {
      total = e.detail && e.detail.value ? e.detail.value : e.detail
      console.log(total, "0000")
      this.setData(
        this.data.billList[index].money = total,
      )
    } else {
      total = this.data.billList[index].num * this.data.billList[index].price
      console.log(total, "字东计算")
      this.setData(
        this.data.billList[index].money = total,
      )
    }
    // this.setData(
    //     this.data.billList[index].money = total,
    // )

    this.count_price();
  },
  //分组
  ongroupNochange(e) {
    console.log(e.detail)
    let index = e.currentTarget.dataset.index;
    this.setData(
      this.data.billList[index].groupNo = e.detail
    )
  },

  click() {
    let billList = this.data.billList;
    this.setData({
      billList: billList
    })
    this.count_price();
  },
  focus(e) {
    this.setData({
      typeIndex: e.currentTarget.dataset.index, //获取下边
      showType: true,
      content: e.detail.value
    });
    if (e.detail.value == '') {
      this.showList()
    }
  },
  change(e) {
    console.log(e.detail, "change")
    this.setData({
      typeIndex: e.currentTarget.dataset.index, //获取下边
      showType: true,
      content: e.detail
    });
    this.showList()
  },
  iconclick(e) {
    console.log(e, e.currentTarget.dataset.index, 'icon')
    this.setData({
      typeIndex: e.currentTarget.dataset.index, //获取下边
      showType: true,
      content: ''
    });
    this.showList()
  },

  //去选择
  goselect(e) {
    console.log(e, '去选择')
    wx.navigateTo({
      url: '/pages/categorySelection/categorySelection?index= ' + e.currentTarget.dataset.index,
    })
  },

  //货物或应税劳务，服务名称 列表初始渲染
  showList() {
    let that = this;
    api.taskList({
      data: {
        coId: this.data.coId,
        word: this.data.content,
      },
      success: function (res) {
        console.log(res.data.data, "taskList")
        if (res.data.code = 200) {
          that.data.columns = [];
          res.data.data.forEach((item) => {
            let obj = {
              text: item.name,
              code: item.code,
            }
            that.data.columns.push(obj)
            // console.log(that.data.columns, 'oooo')
          });
          that.setData({
            columns: that.data.columns,
          })
          that.setData({
            showType: true
          })
        } else {
          that.setData({
            showType: false
          })
        }
      }
    })
  },
  //点击完成
  onConfirmType(e) {
    const {
      value,
    } = e.detail;
    console.log(value, "val")
    let text = value.text;
    let code = value.code
    console.log(code, "code1")
    this.data.billList[this.data.typeIndex].contentCode = code;
    this.data.billList[this.data.typeIndex].content = e.detail.value.text;
    this.setData({
      billList: this.data.billList,
      content: value.text,
      showType: false,
    })
    // console.log(this.data.columns,'columns')
  },
  //点击取消
  onCancelType() {
    let billList = this.data.billList;
    this.setData({
      billList: billList,
      showType: false
    });
  },
  //点击遮罩层取消
  overlay() {
    this.onCancelType()
  },
  //+增加开票内容
  addCont() {
    let billList = this.data.billList;
    billList.push({
        content: '',
        contentCode: '',
        model: '',
        production: '',
        unit: '',
        num: '',
        price: '',
        money: '',
      }),
      this.setData({
        billList: billList
      })
    console.log(this.data.billList, '+增加开票内容')
  },


  //点击保存
  save() {
    //开票总金额
    let total = 0;
    let that = this;
    that.data.noMoney = false;
    that.data.billList.forEach((item) => {
      total = total + Number(item.money)
      if (!item.production || !item.money) {
        if (!item.production) {
          wx.showToast({
            title: '请填写产品名称',
            icon: 'none'
          })

        } else {
          wx.showToast({
            title: '金额不能为空',
            icon: 'none'
          })
        }
        that.setData({
          noMoney: true
        })
      }
    })
    this.setData({
      totalPrice: total.toFixed(2)
    })
    console.log(total, "total")

    if (!that.data.noMoney) {
      this.baocun()
    }
  },
  baocun() {
    //保存
    console.log(this.data.billList, '保存的时候')
    let that = this;
    api.newtask({
      method: 'POST',
      data: {
        coId: this.data.coId,
        taxRate: this.data.keyId,
        createBy: this.data.unitId,
        invId: this.data.invid,
        list: this.data.billList,
      },
      success: function (res) {
        console.log(res.data.data, "newtask")
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 0,
            })
          }, 100);
        } else {
          wx.showModal({
            content: res.data.message,
            // content:'金额不能为空',
            showCancel: false,
            confirmColor: '#0041C4'
          })
        }
      }
    })
  },

  //删除
  delbillList(e) {
    let index = e.currentTarget.dataset.index;
    let that = this
    Dialog.confirm({
        message: '确定删除吗？',
      })
      .then(() => {
        that.data.billList.splice(index, 1)
        that.setData({
          billList: that.data.billList
        })
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
      })
      .catch(() => {
        // on cancel
        console.log('取消操作')
      });
  },
  //汇总金额
  count_price() {
    let total = 0;
    let that = this;
    that.data.billList.forEach((item) => {
      total = total + Number(item.money)
    })
    that.setData({
      totalPrice: total
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      invid: options.id,
      code: options.code,
      keyId: options.keyId,
      userName: options.userName,
      deptName: options.deptName,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.coId = wx.getStorageSync('userInfo').coId
    this.data.unitId = wx.getStorageSync('userInfo').unitId
// wx.navigateBack({//返回 携带的参数
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];

    console.log(this.data.index,this.data.content, this.data.contentCode)
    let Bindex = parseInt(this.data.index)
    if(this.data.content && this.data.contentCode){
      this.data.billList[Bindex].contentCode = this.data.contentCode,
      this.data.billList[Bindex].content = this.data.content
      this.setData({
        billList: this.data.billList
      })
    console.log(this.data.billList)
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})